/* TSController 
	This class handles the communication between Syncer (the model) and the user interface (the view).
*/


import com.apple.cocoa.foundation.*;
import com.apple.cocoa.application.*;
import java.util.*;

public class TSController implements SyncListener {

    public NSPopUpButton playlistPopUp; /* IBOutlet */
    public NSPopUpButton diskPopUp; /* IBOutlet */
	public NSProgressIndicator progressIndicator; /* IBOutlet */
	public NSTextField statusText; /* IBOutlet */
	public NSButton syncButton; /* IBOutlet */
	public Syncer syncer; /* IBOutlet */
	public NSWindow prefsWindow; /* IBOutlet */
	
	public void preferences(Object sender){
		prefsWindow.makeKeyAndOrderFront(this);
	}
	
    public void sync(Object sender) { /* IBAction */
		notify("Starting sync");
		syncButton.setEnabled(false);
		String playlist = playlistPopUp.titleOfSelectedItem();
		String dest = "/Volumes/"+diskPopUp.titleOfSelectedItem();
		double d = (double)syncer.setDest(dest);
		double p = (double)syncer.setPlaylist(playlist);
		progressIndicator.setDoubleValue(0);
		progressIndicator.setMaxValue(d+p);

		
		// Launch the Syncer in its own thread since we want to be able to
		// change the status of the user interface
		new SyncerThread(syncer).start();
    }
	
	public void changePlaylist(Object Sender){
	//	System.out.println("Du skiftede playlist");		
	}

	public void changeDisk(Object Sender){
	//	System.out.println("Du skiftede disk");		
	}

/** Method called by UI before it is displayed but after the different objects are initialized */
	public void awakeFromNib() {
		syncer = new Syncer();
		syncer.addListener(this);
		syncer.addListener(new Debugger());
		try {
			NSArray volumes = 	NSWorkspace.sharedWorkspace().mountedRemovableMedia(); // Get rem. volumes
			
			// Populate drop down menues
			diskPopUp.removeAllItems();
			for(int i=0;i<volumes.count();i++){
				diskPopUp.addItem(NSPathUtilities.lastPathComponent((String)(volumes.objectAtIndex(i))));
			}
			
			List<String> playlists = syncer.getPlaylists();
			playlistPopUp.removeAllItems();
			for(String p : playlists ) {
				playlistPopUp.addItem(p);
			}
			
		} catch (Exception e){
			e.printStackTrace();
		}
	
	
	}

	public void notifyDelete(String s){
		progressIndicator.incrementBy(1);
		s = NSPathUtilities.lastPathComponent(s);
		notify("Deleting " + s);
	}

	public void notifyCopy(String s){
		progressIndicator.incrementBy(1);
		s = NSPathUtilities.lastPathComponent(s);
		notify("Copying " + s);
	}

	public void notifyIgnore(String s){
		progressIndicator.incrementBy(1);
		s = NSPathUtilities.lastPathComponent(s);
		notify("Ignoring " + s);
	}

	public void notifyDone(){
		syncButton.setEnabled(true);
		notify("Sync done!");
	}

	public void notify(String msg){
		statusText.setStringValue(msg);
		
	}
}
